using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour
{

	public float maxVelocity = 50;
	public float minVelocity = 30;
		
	
	//public bool mbIsPegamento = false;
	public bool mbActiva = true;
	
	private float mfVelocidadZ = 30;
	private float mfVelocidadX = 5;
	
	
	
	void Awake()
	{
		if (mbActiva)
		  rigidbody.velocity = new Vector3(0, 0, mfVelocidadZ);
	}

	void Update()
	{
			
		if (mbActiva == false)  //bola pegada
		{
			GameObject lgoPaddle = GameObject.Find(BreakoutGame.SP.NombrePaddle);
			this.transform.parent = lgoPaddle.transform;

			

			//print("UpdateBall: BolaPegada");
			
			
			
			
		}
		

		if ((Input.GetKeyDown("space") || (BreakoutGame.SP.mbTouch)) && (!mbActiva))
		//if ((Input.GetKeyDown("space") || (Input.touches[0].phase == TouchPhase.Began))&& (!mbActiva))
		{
			rigidbody.velocity = new Vector3(mfVelocidadX, 0, mfVelocidadZ);
			mbActiva = true;
			BreakoutGame.SP.mbTouch = false;
			this.transform.parent = null;
			print("espacio en Ball:Update()");
		}
		else if (mbActiva)
		{
			//Asegurate que estamos siempre entre la velocidad MAX y MIN.
			float totalVelocity = Vector3.Magnitude(rigidbody.velocity);
	
			if (totalVelocity < minVelocity)
			{
				float tooSlowRate = totalVelocity / minVelocity;
				rigidbody.velocity /= tooSlowRate;
			}
	
			//La pelota está a una altura de -20? Entonces has perdido.
			if (transform.position.z <= -20)
			{
				BreakoutGame.SP.LostBall();
				Destroy(gameObject);
			}
		}
	
	}
	
	
	
	void OnCollisionEnter (Collision lCollision)
	{

		if ((lCollision.collider.tag == "GameController"))
			Sonidos.SP.Choque("BolaPaddle");
			
		if ((lCollision.collider.tag == "GameController") && (BreakoutGame.SP.meRegaloActual == eRegalos.Pegamento))
		{
			Debug.Log("Ball: OnCollisionEnter " + lCollision.collider.transform.position.x.ToString());
			
			
			//Sonidos.SP.Choque("BolaBloque");
			
			
			//Vector3 lPositionPaddle = GameObject.Find(BreakoutGame.SP.NombrePaddle).transform.position;
			Vector3 lPositionBola;
			//lPositionPaddle.z += 2.5f;
			//lPositionBola.z = lCollision.collider.transform.position.z + 2.5f;
			lPositionBola.x = this.transform.position.x;
			lPositionBola.y = this.transform.position.y;
			lPositionBola.z = this.transform.position.z - 1.5f;			
			this.transform.position = lPositionBola;
			

			

			this.rigidbody.velocity = Vector3.zero;
			this.mbActiva = false;
		}
		
	}
	
	
	
	
}
